#include "plannermodel.h"

const char *PlannerModel::TITLE_STR = "title";
const char *PlannerModel::DATE_STR = "date";
const char *PlannerModel::DESCRIPTION_STR = "description";
const char *PlannerModel::STATE_STR = "state";

QList<Plan *> PlannerModel::m_plans;
QObject PlannerModel::gparent;

PlannerModel::PlannerModel(QObject *parent) :
  QAbstractListModel(parent)
{
}

int PlannerModel::rowCount(const QModelIndex &parent) const
{
  Q_UNUSED(parent);
  return m_plans.count();
}

QVariant PlannerModel::data(const QModelIndex &index, int role) const
{
  if(role == PlannerModel::TITLE)
    return m_plans.at(index.row())->title();
  if(role == PlannerModel::DATE)
    return m_plans.at(index.row())->date();
  if(role == PlannerModel::DESCRIPTION)
    return m_plans.at(index.row())->description();
  if(role == PlannerModel::STATE)
    return m_plans.at(index.row())->state();
  if(role == Qt::DisplayRole)
    return m_plans.at(index.row())->title();
  return QVariant();
}

Qt::ItemFlags PlannerModel::flags(const QModelIndex &index) const
{
  return QAbstractListModel::flags(index) | Qt::ItemIsEditable;
}

QHash<int, QByteArray> PlannerModel::roleNames() const
{
  QHash<int, QByteArray> hash = QAbstractListModel::roleNames();
  hash[TITLE] = TITLE_STR;
  hash[DATE] = DATE_STR;
  hash[DESCRIPTION] = DESCRIPTION_STR;
  hash[STATE] = STATE_STR;
  return hash;
}

bool PlannerModel::insertRows(int row, int count, const QModelIndex &parent)
{
  beginInsertRows(parent, row, row + count - 1);
  endInsertRows();
  return true;
}

bool PlannerModel::removeRows(int row, int count, const QModelIndex &parent)
{
  beginRemoveRows(parent, row, row + count - 1);
  endRemoveRows();
  return true;
}

void PlannerModel::prepend(Plan *p)
{
  p->setParent(&gparent);
  m_plans.prepend(p);
  insertRow(0, QModelIndex());
}

void PlannerModel::remove(int i)
{
  m_plans[i]->deleteLater();
  m_plans.removeAt(i);
  removeRow(i, QModelIndex());
}
